package com.fingard.dsp.bank.directbank.cpcn01;

import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IRealTime;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingle;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingle;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.text.Base64Helper;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * 中金渠道单笔实时代收 
 */
public class CPCN01RealTime extends CPCN01Base implements IRealTime {

	public RetAtsSingle d_9108_RealTimeRec(ReqSingle p_req9108)	throws Exception{
		RetAtsSingle retAts = new RetAtsSingle(p_req9108.reqHeader);
		if ("910801".equals(p_req9108.reqHeader.commandCode)) {
			retAts = d_910801_RealTimeRec(p_req9108);
		}
		return retAts;
	}

	/**
	 * 单笔实时代收
	 */
	public RetAtsSingle d_910801_RealTimeRec(ReqSingle p_req9108)	throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req9108.reqHeader);
		RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
		
		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_req9108.singleDetail.recAct, "");
			if (actItem == null || !FileHelper.existFile(actItem.ownKeyStorePath)|| !FileHelper.existFile(actItem.oppCertFilePath)) {
				if (actItem == null) {
					throw new Exception("未找到账号" + p_req9108.singleDetail.recAct + "对应的商户配置节点");
				} else {
					throw new Exception("账号" + p_req9108.singleDetail.recAct + "对应的证书文件不存在");
				}
			}
			
			CPCN01Header bankHeader = new CPCN01Header();
			bankHeader.transCode = "2011";
			
			XmlTextWriter xmlWriter = new XmlTextWriter();
			writeCommonHeader(xmlWriter, bankHeader);
			
			xmlWriter.writeElementString("InstitutionID", actItem.merchantId);
			xmlWriter.writeElementString("TxCode", bankHeader.transCode);
			xmlWriter.writeElementString("TxSN", p_req9108.singleDetail.askNumber);
			xmlWriter.writeEndElement();
			xmlWriter.writeStartElement("Body");
			xmlWriter.writeElementString("Amount", StringHelper.amountMultiply100(p_req9108.singleDetail.payAmount));
			xmlWriter.writeElementString("BankID", getBankConfig().getMapValueByKey("bankMapping", p_req9108.singleDetail.payBankCode));// 银行数字编码
			
			if (p_req9108.singleDetail.isPrivate.equals("1")) {
				xmlWriter.writeElementString("AccountType", "11");//个人账户
			}else {
				xmlWriter.writeElementString("AccountType", "12");//企业账户
			}
			
			if (p_req9108.singleDetail.cardType.equals("3")) {
				String expiredDate = p_req9108.singleDetail.expiredDate;
				if (StringHelper.hasAnyChar(expiredDate)) {
					expiredDate = expiredDate.substring(2, 4) + expiredDate.substring(0, 2);
				}
				xmlWriter.writeElementString("ValidDate", expiredDate);
				xmlWriter.writeElementString("CVN2", p_req9108.singleDetail.cvv2);
			}
			
			xmlWriter.writeElementString("AccountName", p_req9108.singleDetail.payName);
			xmlWriter.writeElementString("AccountNumber", p_req9108.singleDetail.payAct);
			xmlWriter.writeElementString("BranchName", p_req9108.singleDetail.payBankLocation);// 分支行名称
			xmlWriter.writeElementString("Province", p_req9108.singleDetail.getOppProvinceAndCity()[0]);
			xmlWriter.writeElementString("City", p_req9108.singleDetail.getOppProvinceAndCity()[1]);
			xmlWriter.writeElementString("IdentificationType", convertCertTypeToBank(p_req9108.singleDetail.certType));// 证件类型
			xmlWriter.writeElementString("IdentificationNumber", p_req9108.singleDetail.certNum);// 证件号码
			xmlWriter.writeElementString("Note", p_req9108.singleDetail.memo);// 备注
			xmlWriter.writeElementString("ContractUserID", p_req9108.singleDetail.authAgNum);// 协议编号
			xmlWriter.writeElementString("PhoneNumber", p_req9108.singleDetail.cellPhone);
			xmlWriter.writeElementString("SplitType", "10");
			xmlWriter.writeElementString("SettlementFlag", "0002");// 结算标识 (默认为"0001")

			String cardType = p_req9108.singleDetail.cardType;
			if (StringHelper.hasAnyChar(cardType)) {
				xmlWriter.writeElementString("CardMediaType", convertCardTypeMapping(cardType));//不上送，默认为借记卡
			}else {
				xmlWriter.writeElementString("CardMediaType", "");
			}
			xmlWriter.writeEndElement();
			xmlWriter.writeEndDocument();
			
			// 请求报文
			WriteBankLogStep2(xmlWriter.toXmlString());	 
			
			String[] tmpStrRet = sendToBank("sync", xmlWriter.toXmlString(), actItem);
			
			if (tmpStrRet[0].length() == 0) {
				String[] respInfo = tmpStrRet[1].split(",");
				String respXml = Base64Helper.getFromBase64(respInfo[0], getCharset());
				
				WriteBankLogLn("银行返回的报文为：" + respXml);
				
				StringBuilder tmpSbMsg = new StringBuilder();
				XmlTextReader tmpBkReader = loadBankRespXmlReader(respXml, tmpSbMsg);
				
				if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/Response/Head/Code");
					
					if (tmpRetCode.equals("2000")) {
						tmpRetDetail.respCode = "0";
						tmpRetDetail.reqSeqID = tmpBkReader.getFirstText("/Response/Body/TxSN");
						String transAmt = tmpBkReader.getFirstText("/Response/Body/Amount");
						tmpRetDetail.transAmt = StringHelper.amountDivide100(transAmt);
						tmpRetDetail.transState = tmpBkReader.getFirstText("/Response/Body/Status");
                        tmpRetDetail.respInfo = tmpBkReader.getFirstText("/Response/Body/ResponseMessage");
                        tmpRetDetail.payInfoCode = tmpBkReader.getFirstText("/Response/Body/ResponseCode");
					}else {
						tmpRetDetail.respCode = "-1";
						tmpRetDetail.respInfo = tmpBkReader.getFirstText("/Response/Head/Message");
					}
				}else {
					tmpRetDetail.respCode = "-1";
					tmpRetDetail.respInfo = tmpSbMsg.toString();
				}
			} else if (tmpStrRet[0].equals(ConnState.FAIL) || tmpStrRet[0].equals(FailCode.E9981)) {
				tmpRetDetail.respCode = "0";
				tmpRetDetail.respInfo = tmpStrRet[1];
				tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
				tmpRetDetail.transState = PaymentState.FAIL_Batch;
				tmpRetDetail.payInfoCode = tmpStrRet[0];
			} else {
				tmpRetDetail.respCode = "-1";
				tmpRetDetail.respInfo = tmpStrRet[1];
			}
		} catch (Exception e) {
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = e.toString();
			e.printStackTrace();
		}
		
		if (tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
			tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
		}
		
		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}

	/**
	 * 单笔实时代扣交易状态查询
	 */
	public RetAtsSingle d_9144_QryRealTimeRec(ReqQrySingle p_req9144) throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req9144.reqHeader);
		RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
		
		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_req9144.recAct, "");
			if (actItem == null || !FileHelper.existFile(actItem.ownKeyStorePath)|| !FileHelper.existFile(actItem.oppCertFilePath)) {
				if (actItem == null) {
					throw new Exception("未找到账号" + p_req9144.recAct + "对应的商户配置节点");
				} else {
					throw new Exception("账号" + p_req9144.recAct + "对应的证书文件不存在");
				}
			}
		
			CPCN01Header bankHeader = new CPCN01Header();
			bankHeader.transCode = "2020";
		
			// 拼接请求报文
			XmlTextWriter xmlWriter = new XmlTextWriter();
			writeCommonHeader(xmlWriter, bankHeader);
			
			xmlWriter.writeElementString("InstitutionID", actItem.merchantId);// 机构编号
			xmlWriter.writeElementString("TxCode", bankHeader.transCode);// 交易编码
			xmlWriter.writeElementString("TxSN", p_req9144.askNumber);//交易流水
			xmlWriter.writeEndElement();
			xmlWriter.writeEndDocument();
		
			String[] tmpStrRet = sendToBank("sync", xmlWriter.toXmlString(), actItem);
			
			if (tmpStrRet[0].length() == 0) {
				String[] respInfo = tmpStrRet[1].split(",");
				String respXml = Base64Helper.getFromBase64(respInfo[0], getCharset());
				
				WriteBankLogLn("中金返回的报文为：" + respXml);
				
				StringBuilder tmpSbMsg = new StringBuilder();
				XmlTextReader tmpBkReader = loadBankRespXmlReader(respXml, tmpSbMsg);
				
				if (tmpBkReader != null) {
					String tmpRespCode = tmpBkReader.getFirstText("/Response/Head/Code");
					
					if (tmpRespCode.equals("2000")) {
						tmpRetDetail.respCode = "0";
						tmpRetDetail.respInfo = tmpBkReader.getFirstText("/Response/Body/ResponseMessage");
						tmpRetDetail.reqSeqID = tmpBkReader.getFirstText("/Response/Body/TxSN");
						String transAmt = tmpBkReader.getFirstText("/Response/Body/Amount");
						tmpRetDetail.transAmt = StringHelper.amountDivide100(transAmt);
						tmpRetDetail.transState = tmpBkReader.getFirstText("/Response/Body/Status");
						tmpRetDetail.payInfoCode = tmpBkReader.getFirstText("/Response/Body/ResponseCode");
					}else {
						tmpRetDetail.respCode = "0";
						tmpRetDetail.respInfo = tmpBkReader.getFirstText("/Response/Head/Message");
						tmpRetDetail.transState = tmpRespCode;
						tmpRetDetail.payInfoCode =tmpRespCode;
					}
				}else {
					tmpRetDetail.respCode = "-1";
					tmpRetDetail.respInfo = tmpSbMsg.toString();
				}
			} else {
				tmpRetDetail.respCode = "-1";
				tmpRetDetail.respInfo = tmpStrRet[1];
			}
		} catch (Exception e) {
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = e.getMessage();
			e.printStackTrace();
		}
		
		if (tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
			tmpRetDetail.reqSeqID = p_req9144.askNumber;
		}
		
		if (tmpRetDetail.respCode.equals("-1")) {
			retAts.writeRetDetail(tmpRetDetail);
		}
		
		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}
}
